//
//  OrderListViewController.m
//  much
//
//  Created by Believer Just on 2019/1/11.
//  Copyright © 2019年 iOS. All rights reserved.
//

#import "OrderListViewController.h"
#import "OrderListTableViewCell.h"
#import "OrderDetailViewController.h"
#import "OrderListHeaderView.h"
/**
#import "MyOrderListFooterView.h"
#import "NewStoreRefundViewController.h"
#import "NewStoreNewRefundViewController.h"
#import "PaySelectViewController.h"
#import "BasicWebViewController.h"
#import "PayResultViewController.h"
#import "PayOrderRequestManager.h"
#import "PurchaseListTableViewCell.h"
#import "PurchaseListTableViewFooterView.h"
#import "PurchaseDetailViewController.h"
#import "NewStoreNewRefundDetailViewController.h"
#import "NSNRSingleRefundListVC.h"
#import "AppraiseListBaseViewController.h"
 */

@interface OrderListViewController () <UITableViewDataSource, UITableViewDelegate> {
    BOOL _updateRequest;
}

/**
@property (assign, nonatomic) NSInteger ablePointCount;
 */
@property (strong, nonatomic) UITableView * tableView;

@property (nonatomic, strong) UIView *topBgView;
@property (nonatomic, strong) UIButton *orderButton;
@property (nonatomic, strong) UIView *orderButtonLineView;
@property (nonatomic, strong) UIButton *shopButton;
@property (nonatomic, strong) UIView *shopButtonLineView;

@property (nonatomic, assign) NSInteger topViewButtonTag;
@property (nonatomic, assign) BOOL isClickMessage;

@end

@implementation OrderListViewController

- (void)_reLayout {
    /**
     self.ablePointCount = USER.userBaseInfo.account.point;
     */
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (self.topViewButtonTag == TopViewButtonTagOrder || self.topViewButtonTag == TopViewButtonTagRefundOrder) {
        [self loadDataWithPage:1];
        _couldSendRequest = YES;
    } else {
        [self loadShopDataWithPage:1];
        _couldSendRequest = YES;
    }
    
    [self updateViewShow];
}
- (void)updateViewShow {
    if (self.index == 6) {
        [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.topBgView.mas_bottom);
            make.left.equalTo(self.view);
            make.bottom.equalTo(self.view);
            make.right.equalTo(self.view);
        }];
    } else {
        [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view);
            make.top.equalTo(self.view);
            make.bottom.equalTo(self.view);
            make.right.equalTo(self.view);
        }];
    }
}
- (void)progressTopViewButton:(UIButton *)sender {
    if (_couldSendRequest) {
        self.topViewButtonTag = sender.tag;
        switch (sender.tag) {
            case TopViewButtonTagOrder: {
                [self.orderButton setTitleColor:Color175030 forState:UIControlStateNormal];
                self.orderButtonLineView.hidden = NO;
                
                [self.shopButton setTitleColor:Color34 forState:UIControlStateNormal];
                self.shopButtonLineView.hidden = YES;
                self.topViewButtonTag = TopViewButtonTagRefundOrder;
                [self loadDataWithPage:1];
                break;
            }
            case TopViewButtonTagShop: {
                [self.orderButton setTitleColor:Color34 forState:UIControlStateNormal];
                self.orderButtonLineView.hidden = YES;
                
                [self.shopButton setTitleColor:Color175030 forState:UIControlStateNormal];
                self.shopButtonLineView.hidden = NO;
                
                [self loadShopDataWithPage:1];
                break;
            }
            default:
                break;
        }
    }
}
- (void)loadDataWithPage:(NSInteger)page {
    _couldSendRequest = NO;
    [SVProgressHUD showWithStatus:@"加载中"];
    self.tableView.tableFooterView = [UIView new];
    if (self.index != 5) {
        NSInteger httpIndex = self.index == 6 ? 5 : self.index;
        /**
        [StoreRequestManager userGetOrderListWithOrderState:httpIndex page:page title:self.searchContent sucess:^(NSArray * data) {
            [SVProgressHUD dismiss];
            if (page > 1) {
                [self.tableView.mj_footer endRefreshing];
                if (data.count == 0) {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            } else {
                self.tableView.mj_footer.state = MJRefreshStateIdle;
                if (data.count == 0) {
                    NullStateViewType type = self.searchContent.hasValue ? NoSearchOrderResultsType : OrderListEmptyType;
                    NullStateView *nullStateView = [[NullStateView alloc] initWithFrame:self.tableView.frame fromViewType:type];
                    self.tableView.tableFooterView = nullStateView;
                }
                self.tableView.page = 1;
                [self.tableView.mj_header endRefreshing];
                [self.tableView.dataArray removeAllObjects];
                [self.tableView setContentOffset:CGPointMake(0,0) animated:NO];
            }
            
            [self.tableView.dataArray addObjectsFromArray:data];
            self.tableView.page++;
            if (TotalCount == self.tableView.dataArray.count) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            _couldSendRequest = YES;
            [self.tableView reloadData];
        } fail:^(NSString * error) {
            [SVProgressHUD dismiss];
            if (page > 1) {
                [self.tableView.mj_footer endRefreshing];
            } else {
                [self.tableView.mj_header endRefreshing];
            }
            ErrorMessageModel * errorModel = [[ErrorMessageModel alloc] initWithString:error error:nil];
            if (errorModel.code == HttpResultCodePaySUCCESS || errorModel.code == HttpResultCodeGoodsOutline) {
                [SVProgressHUD showErrorWithStatus:errorModel.message];
                [self loadDataWithPage:1];
            }
            _couldSendRequest = YES;
        }];
         */
    } else {
        /**
        [StoreRequestManager userGetOrderListWithOrderPurchaseState:page sucess:^(NSArray * data) {
            [SVProgressHUD dismiss];
            if (page > 1) {
                [self.tableView.mj_footer endRefreshing];
                if (data.count == 0) {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            } else {
                self.tableView.mj_footer.state = MJRefreshStateIdle;
                if (data.count == 0) {
                    NullStateView *nullStateView = [[NullStateView alloc] initWithFrame:self.tableView.frame fromViewType:OrderListEmptyType];
                    self.tableView.tableFooterView = nullStateView;
                }
                self.tableView.page = 1;
                [self.tableView.mj_header endRefreshing];
                [self.tableView.dataArray removeAllObjects];
                [self.tableView setContentOffset:CGPointMake(0,0) animated:NO];
            }
            
            [self.tableView.dataArray addObjectsFromArray:data];
            self.tableView.page++;
            if (TotalCount == self.tableView.dataArray.count) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            _couldSendRequest = YES;
            [self.tableView reloadData];
        } fail:^(NSString *error) {
            [SVProgressHUD dismiss];
            if (page > 1) {
                [self.tableView.mj_footer endRefreshing];
            } else {
                [self.tableView.mj_header endRefreshing];
            }
            
            ErrorMessageModel * errorModel = [[ErrorMessageModel alloc] initWithString:error error:nil];
            if (errorModel.code == HttpResultCodePaySUCCESS || errorModel.code == HttpResultCodeGoodsOutline) {
                [SVProgressHUD showErrorWithStatus:errorModel.message];
                [self loadDataWithPage:1];
            }
            _couldSendRequest = YES;
        }];
         */
    }
}
- (void)loadShopDataWithPage:(NSInteger)page {
    _couldSendRequest = NO;
    [SVProgressHUD showWithStatus:@"加载中"];
    self.tableView.tableFooterView = [UIView new];
    /**
    [StoreRequestManager userGetShopOrderList:page sucess:^(NSArray * data) {
        [SVProgressHUD dismiss];
        if (page > 1) {
            [self.tableView.mj_footer endRefreshing];
            if (data.count == 0) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        } else {
            self.tableView.mj_footer.state = MJRefreshStateIdle;
            if (data.count == 0) {
                NullStateView *nullStateView = [[NullStateView alloc] initWithFrame:self.tableView.frame fromViewType:OrderListEmptyType];
                self.tableView.tableFooterView = nullStateView;
            }
            self.tableView.page = 1;
            [self.tableView.mj_header endRefreshing];
            [self.tableView.dataArray removeAllObjects];
            [self.tableView setContentOffset:CGPointMake(0,0) animated:NO];
        }
        
        [self.tableView.dataArray addObjectsFromArray:data];
        self.tableView.page++;
        if (TotalCount == self.tableView.dataArray.count) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        _couldSendRequest = YES;
        [self.tableView reloadData];
    } fail:^(NSString *error) {
        [SVProgressHUD dismiss];
        if (page > 1) {
            [self.tableView.mj_footer endRefreshing];
        } else {
            [self.tableView.mj_header endRefreshing];
        }
        
        ErrorMessageModel * errorModel = [[ErrorMessageModel alloc] initWithString:error error:nil];
        if (errorModel.code == HttpResultCodePaySUCCESS || errorModel.code == HttpResultCodeGoodsOutline) {
            [SVProgressHUD showErrorWithStatus:errorModel.message];
            [self loadShopDataWithPage:1];
        }
        
        _couldSendRequest = YES;
    }];
     */
}
/** 退换货按钮事件 */
- (void)refundActionWithModel:(Orders *)model {
    /**
    if (model.orderStateIndex == OrderStateSuccess) {
        if (model.couponType.hasValue) {
            if ([model.couponType isEqualToString:@"goods_coupon"] || [model.couponType isEqualToString:@"cash_coupon"]) {
                NewBaseAlertView * newBaseAlertView = [[NewBaseAlertView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) Message:@"申请换货" Distruction:[NSString stringWithFormat:@"申请换货请拨打服务热线：\n%@", model.customerServicePhone] CancelButtonTitle:@"暂不换货" SureButtonTitle:@"拨打电话" ButtonNum:2 alertType:NewBaseAlertViewRefoundType];
                newBaseAlertView.newBaseAlertViewBlock = ^(NewBaseAlertViewButtonType type) {
                    switch (type) {
                        case NewBAVCancelBtnType:
                            break;
                        case NewBAVSureBtnType: {
                            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", model.customerServicePhone]]];
                            break;
                        }
                        default:
                            break;
                    }
                };
                TYAlertController *alertController = [TYAlertController alertControllerWithAlertView:newBaseAlertView preferredStyle:TYAlertControllerStyleActionSheet];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        } else {
            [self pushToRefundVC:model];
        }
    } else {
        [self pushToRefundVC:model];
    }
     */
}
- (void)newRefundActionWithModel:(GoodsModel *)model orderModel:(Orders *)orderModel {
    /**
    if (orderModel.orderStateIndex == OrderStateSuccess) {
        if ([model.couponType isEqualToString:@"goods_coupon"] || [model.couponType isEqualToString:@"cash_coupon"]) {
            NewBaseAlertView * newBaseAlertView = [[NewBaseAlertView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) Message:@"申请换货" Distruction:[NSString stringWithFormat:@"申请换货请拨打服务热线：\n%@", model.customerServicePhone] CancelButtonTitle:@"暂不换货" SureButtonTitle:@"拨打电话" ButtonNum:2 alertType:NewBaseAlertViewRefoundType];
            newBaseAlertView.newBaseAlertViewBlock = ^(NewBaseAlertViewButtonType type) {
                switch (type) {
                    case NewBAVCancelBtnType:
                        break;
                    case NewBAVSureBtnType: {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", model.customerServicePhone]]];
                        break;
                    }
                    default:
                        break;
                }
            };
            TYAlertController *alertController = [TYAlertController alertControllerWithAlertView:newBaseAlertView preferredStyle:TYAlertControllerStyleActionSheet];
            [self presentViewController:alertController animated:YES completion:nil];
        } else {
            [self pushToNewRefundVC:model orderModel:orderModel];
        }
    } else {
        [self pushToNewRefundVC:model orderModel:orderModel];
    }
     */
}
- (void)pushToRefundVC:(Orders *)model {
    /*
    NewStoreRefundViewController * vc = [[NewStoreRefundViewController alloc] init];
    vc.orderId = model.orderId;
    vc.type = 1;
    vc.refundSubmitSuccess = ^() {
        [self.tableView.mj_header beginRefreshing];
    };
    if (model.orderStateIndex == OrderStateDeliveryPending) {
        vc.refundVCType = NewStoreNewRefundVCNormalOnlyType;
    } else {
        vc.refundVCType = NewStoreNewRefundVCNormalType;
    }
    [APP.rootNavigationController pushViewController:vc animated:YES];
     */
}
- (void)pushToNewRefundVC:(GoodsModel *)model orderModel:(Orders *)orderModel {
    /**
    NewStoreNewRefundViewController *vc = [[NewStoreNewRefundViewController alloc] init];
    vc.model = model;
    vc.refundSubmitSuccess = ^(NSString *refundId) {
        [self.tableView.mj_header beginRefreshing];
    };
    if (orderModel.orderStateIndex == OrderStateDeliveryPending) {
        vc.refundVCType = NewStoreNewRefundVCNormalOnlyType;
    } else {
        vc.refundVCType = NewStoreNewRefundVCNormalType;
    }
    [APP.rootNavigationController pushViewController:vc animated:YES];
     */
}
- (void)pushToSingleRefundListVC:(GoodsModel *)model orderModel:(Orders *)orderModel {
    /**
    NSNRSingleRefundListVC *vc = [[NSNRSingleRefundListVC alloc] init];
    vc.goodsModel = model;
    vc.ordersModel = orderModel;
    [APP.rootNavigationController pushViewController:vc animated:YES];
     */
}

/** 支付  */
- (void)payOrder:(Orders *)model {
    /**
    if (model.benefit == JoinHuiyuanMallType) {
        [PayOrderRequestManager loadOrderDataWithPaySelect:PaySelectTypeIntegral type:2 orderId:model.orderId sucess:^(id data) {
            [self pushPayResultControllerVCWithPayResultState:CurrencyExchangeResultsSuccess orderDataModel:model];
        } fail:^(NSString * error) {
            [self pushPayResultControllerVCWithPayResultState:CurrencyExchangeResultsFail orderDataModel:model];
        }];
    } else {
        PaySelectViewController * vc = [[PaySelectViewController alloc] init];
        vc.orderId = model.orderId;
        vc.payType = 2;
        vc.isGroupBuying = model.groupBuying;
        vc.groupSpuSid = model.groupBuyingSid;
        
        vc.needPayMoney = model.realAmount;
        vc.orderTypeString = @"1";
        [APP.rootNavigationController pushViewController:vc animated:YES];
    }
     */
}
/** 确认收货 */
- (void)sureHavaReceiveGoodsWithOrder:(Orders *)model {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:@"您是否已收到该订单商品？" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"未收货" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];
    
    UIAlertAction * sureAction = [UIAlertAction actionWithTitle:@"已收货" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        /**
        [StoreRequestManager userSureHaveReceivedGoodsWithOrderId:model.orderId sucess:^(id data) {
            [self.tableView.dataArray enumerateObjectsUsingBlock:^(Orders * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj.orderId isEqualToString:model.orderId]) {
                    [self.tableView.dataArray removeObjectAtIndex:idx];
                    * stop = YES;
                }
            }];
            [self.tableView reloadData];
            
            // 跳转到评价中心
            AppraiseListBaseViewController *vc = [[AppraiseListBaseViewController alloc] init];
            [APP.rootNavigationController pushViewController:vc animated:YES];
            
        } fail:^(NSString * error) {
            [SVProgressHUD showErrorWithStatus:error];
        }];
         */
    }];
    [alertController addAction:sureAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}
/** 删除订单 */
- (void)deleteOrderWithOrder:(Orders *)model {
    NewBaseAlertView * newBaseAlertView = [[NewBaseAlertView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) Message:@"" Distruction:@"确认删除此订单？" CancelButtonTitle:@"取消" SureButtonTitle:@"删除" ButtonNum:2 alertType:NewBaseAlertViewNormalType];
    __weakConfigure
    newBaseAlertView.newBaseAlertViewBlock = ^(NewBaseAlertViewButtonType type) {
        switch (type) {
            case NewBAVCancelBtnType:
                
                break;
            case NewBAVSureBtnType: {
                /**
                [StoreRequestManager userDeleteOrderWithOrderId:model.orderId sucess:^(id data) {
                    [__weakSelf.tableView.dataArray enumerateObjectsUsingBlock:^(Orders * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        if ([obj.orderId isEqualToString:model.orderId]) {
                            [self.tableView.dataArray removeObjectAtIndex:idx];
                            * stop = YES;
                        }
                    }];
                    [__weakSelf.tableView reloadData];
                } fail:^(NSString * error) {
                    [SVProgressHUD showErrorWithStatus:error];
                }];
                 */
                break;
            }
            default:
                break;
        }
    };
    TYAlertController *alertController = [TYAlertController alertControllerWithAlertView:newBaseAlertView preferredStyle:TYAlertControllerStyleActionSheet];
    [self presentViewController:alertController animated:YES completion:nil];
}
/** 取消订单 */
- (void)cancelOrderWithOrder:(Orders *)model {
    NewBaseAlertView * newBaseAlertView = [[NewBaseAlertView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) Message:@"" Distruction:@"我还在等着你，三思啊～" CancelButtonTitle:@"考虑一下" SureButtonTitle:@"坚决离开" ButtonNum:2 alertType:NewBaseAlertViewNormalType];
    __weakConfigure
    newBaseAlertView.newBaseAlertViewBlock = ^(NewBaseAlertViewButtonType type) {
        switch (type) {
            case NewBAVCancelBtnType:
                
                break;
            case NewBAVSureBtnType: {
                /**
                [StoreRequestManager userCancelOrderWithOrderId:model.orderId sucess:^(id data) {
                    [__weakSelf.tableView.dataArray enumerateObjectsUsingBlock:^(Orders * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        if ([obj.orderId isEqualToString:model.orderId]) {
                            [self.tableView.dataArray removeObjectAtIndex:idx];
                            * stop = YES;
                        }
                    }];
                    [__weakSelf.tableView reloadData];
                } fail:^(NSString *error) {
                    [SVProgressHUD showErrorWithStatus:error];
                }];
                 */
                break;
            }
            default:
                break;
        }
    };
    TYAlertController *alertController = [TYAlertController alertControllerWithAlertView:newBaseAlertView preferredStyle:TYAlertControllerStyleActionSheet];
    [self presentViewController:alertController animated:YES completion:nil];
}
/** 查看物流 */
- (void)showLogistics:(Orders *)model {
    /**
    if (model.transportIds.hasValue) {
        NSString *urlString = [[NSString stringWithFormat:@"%@?company=%@&transportId=%@", kLogisticsBasicURL, model.transportCompanys, model.transportIds] urlEncode];
        BasicWebViewController *vc = [[BasicWebViewController alloc] initWithURL:urlString title:@"物流查询"];
        [APP.rootNavigationController pushViewController:vc animated:YES];
    } else {
        jxt_showAlertTitle(@"暂无物流信息！");
    }
     */
}
/** 退款详情 */
- (void)pushToRefoundDetail:(Orders *)model {
    /**
    NewStoreNewRefundDetailViewController *vc = [[NewStoreNewRefundDetailViewController alloc] init];
    vc.model = model;
    [APP.rootNavigationController pushViewController:vc animated:YES];
     */
}
/** 积分订单支付，这个有可能会用不到，因为后面将积分支付的订单置成支付成功才生成订单 */
/**
- (void)pushPayResultControllerVCWithPayResultState:(PayResultState)state orderDataModel:(Orders *)orderDataModel {
    
    PayResultViewController * vc = [[PayResultViewController alloc] initWithPayResult:state payData:nil orderType:OrderTypeScoreOrder];
    vc.fromControllerResultType = FromControllerResultTypeOrderList;
    orderDataModel.ablePointCount = self.ablePointCount;
    vc.myselfScore = [NSString stringWithFormat:@"%@", @(orderDataModel.ablePointCount - orderDataModel.pointCount)];
    vc.orderUseScore = [NSString stringWithFormat:@"%@", @(orderDataModel.pointCount)];
    vc.payMentAgainBlock = ^(PayResultState result) {
        if (result == CurrencyExchangeResultsSuccess) {
            self.ablePointCount -= orderDataModel.pointCount;
            [self loadDataWithPage:1];
        }
    };
    BasicNavigationController * nav = [[BasicNavigationController alloc] initWithRootViewController:vc];
    [APP.rootNavigationController presentViewController:nav animated:YES completion:nil];
}
 */


#pragma mark - <UITableViewDelegate, UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return tableView.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    Orders *model = [tableView.dataArray objectAtIndex:section];
    return model.spus.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    Orders *model = [tableView.dataArray objectAtIndex:indexPath.section];
    /**
     if (model.orderListPurchaseType == OrderListTypeCommon) {
     */
        OrderListTableViewCell *cell = [OrderListTableViewCell initTableView:tableView];
        __weakConfigure
        cell.orderListCellRefoundButtonBlock = ^(GoodsModel *model, Orders *orderModel) {
            /**
            if (model.groupStyleType == NewStoreDetailGroupHeaderType && [orderModel.realAmount isEqualToString:@"0"]) {
                [__weakSelf alertMessageWithOrderId:orderModel.orderId];
            } else {
                [__weakSelf newRefundActionWithModel:model orderModel:orderModel];
            }
            */
        };
        cell.orderListCellWatchRefoundButtonBlock = ^(GoodsModel *model, Orders *orderModel) {
            [__weakSelf pushToSingleRefundListVC:model orderModel:orderModel];
        };
        return cell;
    /**
     
     } else {
        PurchaseListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[PurchaseListTableViewCell cellClass]];
        if (!cell) {
            cell = [[PurchaseListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[PurchaseListTableViewCell cellClass]];
        }
        return cell;
    }
     */
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    /**
    Orders *model = [tableView.dataArray objectAtIndex:indexPath.section];
    GoodsModel *spuModel = model.spus[indexPath.row];
    spuModel.groupBuying = model.groupBuying;
    if (model.orderListPurchaseType == OrderListTypeCommon) {
        OrderListTableViewCell *orderListCell = (OrderListTableViewCell *)cell;
        spuModel.orderId = model.orderId;
        orderListCell.model = spuModel;
        orderListCell.orderModel = model;
    } else {
        PurchaseListTableViewCell *purchaseListTableViewCell = (PurchaseListTableViewCell *)cell;
        purchaseListTableViewCell.model = spuModel;
    }
     */
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    OrderListHeaderView *headerView = [OrderListHeaderView initTableView:tableView];
    return headerView;
}
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(OrderListHeaderView *)view forSection:(NSInteger)section {
    Orders * model = [tableView.dataArray objectAtIndex:section];
    view.storeName = model.shopName;
    /**
    __weakConfigure
    view.showGroupHeaderBlock = ^{
        [__weakSelf alertMessageWithOrderId:model.orderId];
    };
    if (model.groupHead &&
        ([model.orderStateText isEqualToString:@"待发货"] ||
         [model.orderStateText isEqualToString:@"已关闭"])) { // 拼团商品团长拼
            view.showGroupHeaderMessage = YES;
        } else {
            view.showGroupHeaderMessage = NO;
        }
    if (self.index == 6) {
        view.orderState = model.refundStateText;
    } else {
        if (model.orderListPurchaseType == OrderListTypeCommon) {
            view.orderState = model.orderStateText;
        } else {
            view.model = model;
        }
    }

    [view tapUpWithBlock:^(UIView *v) {
        MerchantModel * merchantModel = [[MerchantModel alloc] init];
        merchantModel.shopSid = model.shopSid;
        merchantModel.shopName = model.shopName;
        [self pushStoreHomeAction:merchantModel];
    }];
     */
}
- (void)alertMessageWithOrderId:(NSString *)orderId {
    if (self.isClickMessage) {
        return;
    }
    self.isClickMessage = YES;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.isClickMessage = NO;
    });
    /**
    [StoreRequestManager storeGroupHeaderOrderShowMessageWithOrderId:orderId sucess:^(NSString *message) {
        jxt_showAlertOneButton(nil, message, @"确定", nil);
        [[UIView appearance] setTintColor:Color175030];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[UIView appearance] setTintColor:[UIColor blackColor]];
        });
    } fail:^(NSString *error) {
        
    }];
     */
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    Orders *model = [tableView.dataArray objectAtIndex:section];
    /**
    if (model.orderListPurchaseType == OrderListTypeCommon) {
        static NSString * identifier = @"footer";
        MyOrderListFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identifier];
        if (!footerView) {
            footerView = [[MyOrderListFooterView alloc] initWithReuseIdentifier:identifier];
        }
        return footerView;
    } else {
        static NSString * identifier = @"purchaseListTableViewFooterView";
        PurchaseListTableViewFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identifier];
        if (!footerView) {
            footerView = [[PurchaseListTableViewFooterView alloc] initWithReuseIdentifier:identifier];
        }
        return footerView;
    }
     */
    UIView *view = [UIView new];
    return view;
}

- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section {
    Orders *model = [tableView.dataArray objectAtIndex:section];
    /**
    if (self.index < 6) {
        model.refundDataModel = NO;
    } else {
        model.refundDataModel = YES;
    }
    if (model.orderListPurchaseType == OrderListTypeCommon) {
        MyOrderListFooterView *myOrderListFooterView = (MyOrderListFooterView *)view;
        model.topShowButtonTag = self.topViewButtonTag;
        myOrderListFooterView.model = model;
        myOrderListFooterView.footerViewBtnBlock = ^(FooterViewBtnType type, Orders * orders) {
            switch (type) {
                case FooterViewBtnTypeApplyRefund:
                    [self refundActionWithModel:orders];
                    break;
                case FooterViewBtnTypePayOrder:
                    [self payOrder:orders];
                    break;
                case FooterViewBtnTypeHasReceived:
                    [self sureHavaReceiveGoodsWithOrder:orders];
                    break;
                case FooterViewBtnTypeDeteleOrder:
                    [self deleteOrderWithOrder:orders];
                    break;
                case FooterViewBtnTypeCancelOrder:
                    [self cancelOrderWithOrder:orders];
                    break;
                case FooterViewBtnTypeLogistics:
                    [self showLogistics:orders];
                    break;
                case FooterViewBtnTypeRefound:
                    [self pushToRefoundDetail:orders];
                    break;
                default:
                    break;
            }
        };
    } else {
        PurchaseListTableViewFooterView *purchaseListTableViewFooterView = (PurchaseListTableViewFooterView *)view;
        purchaseListTableViewFooterView.model = model;
        purchaseListTableViewFooterView.purchaseListTVFButtonBlock = ^(NSInteger buttonTag, Orders *model) {
            switch (buttonTag) {
                case 0:
                    [self approvalMethod:model];
                    break;
                case 1:
                    [self logisticsMethod:model];
                    break;
                case 2:
                    [self sureGetMethod:model];
                    break;
                default:
                    break;
            }
        };
    }
     */
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 122;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    Orders *model = [tableView.dataArray objectAtIndex:section];
    if (self.index == 6) {
        // 退款售后
        if (self.topViewButtonTag == TopViewButtonTagShop || self.topViewButtonTag == TopViewButtonTagRefundOrder) {
            return 40;
        }
        /**
        if (model.orderStateIndex == OrderStateInvalid
            || (model.orderTypeState == OrderTypeSolicitGoods
                && (model.orderStateIndex != OrderStatePayPending
                    && model.orderStateIndex != OrderStateProcessing
                    && model.orderStateIndex != OrderStateProcessing
                    && model.orderStateIndex != OrderStateReceivePending))
            ) {
            return 40;
        }
         */
    }
    /**
    if (model.orderListPurchaseType == OrderListTypeCommon) {
        if (model.orderStateIndex == OrderStateInvalid
            || (model.orderTypeState == OrderTypeSolicitGoods
                && (model.orderStateIndex != OrderStatePayPending
                    && model.orderStateIndex != OrderStateProcessing
                    && model.orderStateIndex != OrderStateProcessing
                    && model.orderStateIndex != OrderStateReceivePending))
            ) {
            return 40;
        }
    } else {
        if (model.orderStateIndex == OrderStateInvalid
            || (model.orderTypeState == OrderTypeSolicitGoods
                && (model.orderStateIndex != OrderStatePayPending
                    && model.orderStateIndex != OrderStateProcessing
                    && model.orderStateIndex != OrderStateProcessing
                    && model.orderStateIndex != OrderStateReceivePending))) {
                    return 40;
                }
    }
     */
    
    return 80;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.index == 6) {
        return;
    }
    OrderDetailViewController * vc = [[OrderDetailViewController alloc] init];
    vc.orderDetailChangeBlock = ^(FooterViewBtnType type, Orders * order) {
        [self.tableView.dataArray enumerateObjectsUsingBlock:^(Orders * obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.orderId isEqualToString:order.orderId]) {
                [self.tableView.dataArray removeObjectAtIndex:idx];
                * stop = YES;
            }
        }];
        [self loadDataWithPage:1];
    };
    vc.order = [tableView.dataArray objectAtIndex:indexPath.section];
    [self.navigationController pushViewController:vc animated:YES];
}
/** 商品审批情况 */
- (void)approvalMethod:(Orders *)model {
    /**
    PurchaseDetailViewController *purchaseDetailVC = [[PurchaseDetailViewController alloc] init];
    purchaseDetailVC.order = model;
    [APP.rootNavigationController pushViewController:purchaseDetailVC animated:YES];
     */
}
/** 商品物流情况 */
- (void)logisticsMethod:(Orders *)model {
    [self showLogistics:model];
}
/** 确认收货 */
- (void)sureGetMethod:(Orders *)model {
    [self sureHavaReceiveGoodsWithOrder:model];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.backgroundColor = HEXCOLOR(0xf4f4f4);
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.delegate = self;
        _tableView.page = 1;
        _tableView.dataArray = [[NSMutableArray alloc] init];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.and.bottom.equalTo(self.view);
            make.top.equalTo(self.navigationView);
        }];
        
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            if (self.topViewButtonTag == TopViewButtonTagOrder || self.topViewButtonTag == TopViewButtonTagRefundOrder) {
                [self loadDataWithPage:1];
            } else {
                [self loadShopDataWithPage:1];
            }
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            if (self.topViewButtonTag == TopViewButtonTagOrder || self.topViewButtonTag == TopViewButtonTagRefundOrder) {
                [self loadDataWithPage:self.tableView.page];
            } else {
                [self loadShopDataWithPage:self.tableView.page];
            }
        }];
    }
    return _tableView;
}

- (UIView *)topBgView {
    if (!_topBgView) {
        _topBgView = [UIView new];
        _topBgView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_topBgView];
        [_topBgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.top.and.right.equalTo(self.view);
            make.height.mas_equalTo(@(33));
        }];
        
        [self progressTopViewButton:self.orderButton];
    }
    return _topBgView;
}
- (UIButton *)orderButton {
    if (!_orderButton) {
        _orderButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [_orderButton setTitle:@"按订单" forState:UIControlStateNormal];
        [_orderButton.titleLabel setFont:APPFONT(14)];
        [_orderButton setTitleColor:Color34 forState:UIControlStateNormal];
        _orderButton.tag = TopViewButtonTagOrder;
        [_orderButton addTarget:self action:@selector(progressTopViewButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.topBgView addSubview:_orderButton];
        [_orderButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.top.and.bottom.equalTo(self.topBgView);
            make.right.equalTo(self.topBgView.mas_centerX);
        }];
    }
    return _orderButton;
}
- (UIView *)orderButtonLineView {
    if (!_orderButtonLineView) {
        _orderButtonLineView = [UIView new];
        _orderButtonLineView.backgroundColor = Color175030;
        [self.topBgView addSubview:_orderButtonLineView];
        [_orderButtonLineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.topBgView);
            make.height.mas_equalTo(@(2));
            make.width.mas_equalTo(@(40));
            make.centerX.equalTo(self.orderButton);
        }];
    }
    return _orderButtonLineView;
}
- (UIButton *)shopButton {
    if (!_shopButton) {
        _shopButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [_shopButton setTitle:@"按商品" forState:UIControlStateNormal];
        [_shopButton.titleLabel setFont:APPFONT(14)];
        [_shopButton setTitleColor:Color34 forState:UIControlStateNormal];
        _shopButton.tag = TopViewButtonTagShop;
        [_shopButton addTarget:self action:@selector(progressTopViewButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.topBgView addSubview:_shopButton];
        [_shopButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.and.top.and.bottom.equalTo(self.topBgView);
            make.left.equalTo(self.topBgView.mas_centerX);
        }];
    }
    return _shopButton;
}
- (UIView *)shopButtonLineView {
    if (!_shopButtonLineView) {
        _shopButtonLineView = [UIView new];
        _shopButtonLineView.backgroundColor = Color175030;
        [self.topBgView addSubview:_shopButtonLineView];
        [_shopButtonLineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.shopButton);
            make.height.mas_equalTo(@(2));
            make.width.mas_equalTo(@(40));
            make.centerX.equalTo(self.shopButton);
        }];
    }
    return _shopButtonLineView;
}

@end
